package cn.itrip.trade.controller;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripHotel;
import cn.itrip.beans.pojo.ItripHotelOrder;
import cn.itrip.common.DtoUtil;
import cn.itrip.trade.service.OrderService;
import cn.itrip.trade.wx.WXPayConstants;
import cn.itrip.trade.wx.WXPayRequest;
import cn.itrip.trade.wx.WXPayUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

@Controller
@RequestMapping("/api/wx")
public class WxPaymentController {

    @Resource
    private OrderService orderService;
    /**
     * 生成微信支付二维码的接口
     * @param orderNo
     * @return
     */
    @RequestMapping(value ="/createcode/{orderNo}",method = RequestMethod.GET)
    public @ResponseBody Dto createCode(@PathVariable String orderNo){
        try {
        Map<String, String> map=new HashMap<String,String>();
        //把微信统一下单的接口需要的必填参数封装进map
        map.put("body","爱旅行微信支付");
        map.put("out_trade_no",orderNo);
        map.put("device_info","");
        map.put("fee_type","CNY");
        map.put("total_fee","1");
        map.put("spbill_create_ip","172.20.10.6");
        //map.put("notify_url","外网可以访问的地址，供微信支付平台回掉项目")
        map.put("notify_url","http://4xssvx.natappfree.cc/trade/api/wx/notify");
        map.put("trade_type","NATIVE");

        map.put("sign_type","MD5");
        map.put("appid","wxab8acb865bb1637e");
        map.put("mch_id","11473623");
        map.put("nonce_str", WXPayUtil.generateNonceStr());
            //把Map转成xml格式发送给微信支付平台
            String requestXML=WXPayUtil.generateSignedXml(map,
                    "2ab9071b06b9f739b950ddb41db2690d", WXPayConstants.SignType.MD5);
            //开始发送请求 URl为微信平台统一下单接口地址
            String responseXML= WXPayRequest.requestWx(
                    "https://api.mch.weixin.qq.com/pay/unifiedorder",requestXML
            );
            //转成Map解析微信返回过来的数据
            Map<String,String>respMap=WXPayUtil.xmlToMap(responseXML);
            //定义Map返回json数据给前台页面
            Map<String,String>resultMap=new HashMap<String, String>();
            //获取关键返回值，判断请求是否成功return_code只是通讯成功
            if(respMap.get("return_code").equals("SUCCESS")&&respMap.get("result_code").equals("SUCCESS")){
                //拿到生成二维码的url地址
                String code_url=respMap.get("code_url");
                resultMap.put("code_url",code_url);
                return DtoUtil.returnDataSuccess(JSON.toJSONString(resultMap));
            }else{
                return DtoUtil.returnFail("return_msg","100002");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
     return DtoUtil.returnFail("发生错误","100001");
    }
    //private Logger logger= LoggerFactory.getLogger(WxPaymentController.class);
    @RequestMapping("/notify")
    @ResponseBody
    public void wxNotify(HttpServletRequest request, HttpServletResponse response)throws Exception{
        //logger.info("++++进入notify页面++++");
        //1.从request获取XML的流转为Map数据
        StringBuffer sb=new StringBuffer();
        InputStream is=request.getInputStream();
        BufferedReader br= new BufferedReader(new InputStreamReader(is,"UTF-8"));
        String temp;
        while ((temp=br.readLine())!=null){
            sb.append(temp);
        }
        br.close();
        is.close();
        Map<String,String>resultMap=WXPayUtil.xmlToMap(sb.toString());
        //验证返回的参数是否合法，需要加签名和key
        boolean flay=WXPayUtil.isSignatureValid(resultMap,
                "2ab9071b06b9f739b950ddb41db2690d", WXPayConstants.SignType.MD5);
        if(flay){
            //2.识别是否成功，修改订单状态
            if(resultMap.get("return_code").equals("SUCCESS")&&resultMap.get("result_code").equals("SUCCESS")){
            //支付成功，进行订单其他的后续业务操作，修改数据
                String out_trade_no=resultMap.get("out_trade_no");
                //微信生成的订单号
                String trade_no=resultMap.get("prepay_id");
                orderService.paySuccess(out_trade_no,2,trade_no);
                //3.返回结果给微信
            Map<String,String>result=new HashMap<>();
            //告诉微信我已经接收到你的异步通知了，你可以不用发送啦
                result.put("return_code","SUCCESS");
                result.put("return_msg","成功");
                String xml=WXPayUtil.generateSignedXml(result,
                        "2ab9071b06b9f739b950ddb41db2690d", WXPayConstants.SignType.MD5);
                response.getWriter().write(xml);
                response.getWriter().flush();
                //静态页面定时函数
            }

        }
    }
    //查询订单是否交易成功
    @RequestMapping("queryOrderStatus/{orderNo}")
    public Dto queryOrderStatus(@PathVariable String orderNo){
        try {
            ItripHotelOrder order=orderService.loadItripHotelOrder(orderNo);
            return DtoUtil.returnDataSuccess(order);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.returnFail("订单不存在","30000");
    }
}
